package com.ndood.polling.app.task;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import com.google.gson.Gson;
import com.ndood.polling.domain.polling.v1.service.PollingService;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 轮询任务：先参考龙果，后期优化
 */
@Getter
@Setter
@Slf4j
public class PollingDelayTask implements Runnable, Delayed{

	private PollingParam param;
	
	private PollingService service;
	
	public PollingDelayTask(PollingParam param, PollingService service) {
		super();
		this.param = param;
		this.service = service;
	}

    /**
     * 比较当前时间(task.executeTime)与任务允许执行的开始时间(executeTime).<br/>
     * 如果当前时间到了或超过任务允许执行的开始时间，那么就返回-1，可以执行。
     */
	@Override
	public int compareTo(Delayed o) {
        PollingDelayTask task = (PollingDelayTask) o;
        Long executeTime = param.getCount() * param.getDuration() + param.getCreateTime().getTime();
        Long taskExecuteTime = task.param.getCount() * task.param.getDuration() + task.param.getCreateTime().getTime();
        return executeTime > taskExecuteTime ? 1 : (executeTime < taskExecuteTime ? -1 : 0);
	}

	@Override
	public long getDelay(TimeUnit unit) {
		Long executeTime = param.getCount() * param.getDuration() + param.getCreateTime().getTime();
		return unit.convert(executeTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
	}

	@Override
	public void run() {
		log.info("执行轮询任务---> "+new Gson().toJson(param));
		service.distributePolling(param);
	}
	
}
